Skip to main content

Mainnet forking

In some cases, you may want to connect to a network using a different chainId than its default. For example, your application is supposed to support the Mainnet network and forked Mainnet chain using Tenderly, so the forked Mainnet should be accessible by a different number than the default chainId of the Mainnet, but the default for both networks it is the same which causes some problems.

Example

So we may want to do something like this:

const config: Config = {
readOnlyChainId: Mainnet.chainId,
readOnlyUrls: {
[Mainnet.chainId]: 'https://mainnet.infura.io/v3/[your-infura-key]',
1337: 'https://rpc.tenderly.co/fork/[your-mainnet-fork-id]',
},
multicallAddresses: {
[Mainnet.chainId]: Mainnet.multicall2Address as string,
1337: Mainnet.multicall2Address as string,
},
multicallVersion: 2 as const,
}

In this case, we want to have our forked Mainnet chain available on chainId: 1337, which is the default for the Ganache network. But this won't work because it generates the provider with the same chainId as the default one, which is 1 for Mainnet.

Solution

We can create a custom provider with overridden chainId:

const customProvider = new providers.StaticJsonRpcProvider('https://rpc.tenderly.co/fork/xxx', {
name: 'mainnet-fork',
chainId: 1337,
})

const config: Config = {
readOnlyChainId: Mainnet.chainId,
readOnlyUrls: {
[Mainnet.chainId]: 'https://mainnet.infura.io/v3/[your-infura-key]',
1337: customProvider,
},
multicallAddresses: {
[Mainnet.chainId]: Mainnet.multicall2Address as string,
1337: Mainnet.multicall2Address as string,
},
multicallVersion: 2 as const,
}